<template>
  <div ref="chartRef" style="width: 100%; height: 500px;"></div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'KLineChart',
  props: {
    klineData: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const chartRef = ref(null);
    const chartInstance = ref(null);

    // 计算移动平均线
    function calculateMA(dayCount, data) {
      const result = [];
      for (let i = 0, len = data.length; i < len; i++) {
        if (i < dayCount) {
          result.push(null); // 替换为 null
          continue;
        }
        let sum = 0;
        for (let j = 0; j < dayCount; j++) {
          sum += +data[i - j][1]; // 收盘价
        }
        result.push(sum / dayCount);
      }
      return result;
    }

    const initChart = () => {
      if (!chartRef.value) return;

      // 如果已经初始化，销毁旧实例
      if (chartInstance.value) {
        chartInstance.value.dispose();
      }

      chartInstance.value = echarts.init(chartRef.value);

      // 将数据转换为 ECharts 需要的格式
      const dates = props.klineData.map(item => item.date);
      const data = props.klineData.map(item => [
        item.open,
        item.close,
        item.low,
        item.high
      ]);

      const option = {
        legend: {
          data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30'],
          inactiveColor: '#777'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false,
            type: 'cross',
            lineStyle: {
              color: '#376df4',
              width: 2,
              opacity: 1
            }
          }
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLine: { lineStyle: { color: '#8392A5' } }
        },
        yAxis: {
          scale: true,
          axisLine: { lineStyle: { color: '#8392A5' } },
          splitLine: { show: false }
        },
        grid: {
          bottom: 80
        },
        dataZoom: [
          {
            textStyle: {
              color: '#8392A5'
            },
            handleIcon:
                'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
            dataBackground: {
              areaStyle: {
                color: '#8392A5'
              },
              lineStyle: {
                opacity: 0.8,
                color: '#8392A5'
              }
            },
            brushSelect: true
          },
          {
            type: 'inside'
          }
        ],
        series: [
          {
            type: 'candlestick',
            name: '日K',
            data: data,
            itemStyle: {
              color: '#FD1050',
              color0: '#0CF49B',
              borderColor: '#FD1050',
              borderColor0: '#0CF49B'
            }
          },
          {
            name: 'MA5',
            type: 'line',
            data: calculateMA(5, data),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 1
            }
          },
          {
            name: 'MA10',
            type: 'line',
            data: calculateMA(10, data),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 1
            }
          },
          {
            name: 'MA20',
            type: 'line',
            data: calculateMA(20, data),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 1
            }
          },
          {
            name: 'MA30',
            type: 'line',
            data: calculateMA(30, data),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 1
            }
          }
        ]
      };

      chartInstance.value.setOption(option);
    };

    const resizeChart = () => {
      if (chartInstance.value) {
        chartInstance.value.resize();
      }
    };

    onMounted(() => {
      initChart();
      window.addEventListener('resize', resizeChart);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', resizeChart);
      if (chartInstance.value) {
        chartInstance.value.dispose();
      }
    });

    // 监听 klineData 的变化，重新初始化图表
    watch(() => props.klineData, () => {
      initChart();
    });

    return {
      chartRef
    };
  }
};
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>